package com.mytrip.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.mytrip.base.exception.BusinessException;

public class UploadUtil{
	private static final Log log = LogFactory.getLog(UploadUtil.class);

	private static final int PIC_FILENAME_LENTH = 8;

	private static final int PIC_FILE_MAX_SIZE = 120;

	public static String uploadTripPic(File file, String fileName){
		int idx = fileName.lastIndexOf(".");
		if (idx == -1) {
			throw new BusinessException("pic_name_error");
		}

		String s = fileName.substring(idx + 1);
		if (!"png".equalsIgnoreCase(s) && !"jpg".equalsIgnoreCase(s) && !"bmp".equals(s)) {
			throw new BusinessException("pic_name_error");
		}

		String name = UsefulUtils.getRandomStr(PIC_FILENAME_LENTH) + "." + s;
		String picPath = Constant.getCommonConf("tripPicPath") + "/" + name;
		try {
			PhotoUtil.alterSize(new FileInputStream(file), new FileOutputStream(new File(Constant
					.getCommonConf("basePicPath")
					+ picPath)), PIC_FILE_MAX_SIZE);
		} catch (FileNotFoundException e) {
			log.warn("", e);
		}
		file.delete();

		return picPath;
	}
}
